var express = require('express')
const {getAuthorityList, newAuthority, delAuthority, getAuthorityDetail} = require("../controller/authority");
const {SuccessModel, ErrorModel} = require("../model/response");
var router = express.Router()

/**
 * 管理员路由操作
 * Role.vue: /new, /del, /list
 * Right.vue: /list/only
 */
// 获取权限列表
router.get('/list', async (req, res, next) => {
  const rights = await getAuthorityList()
  let right = [
    {id: 1, children: [] },
    {id: 2, children: [] },
    {id: 3, children: [] },
  ]
  right.forEach(item => {
    item.children = rights.filter(ele => ele.role_id === item.id && ele.level === 0);
    item.children.forEach(sub => {
      sub.children = rights.filter(thr => thr.pid === sub.id && thr.level === 1);
    })
  })
  res.json(new SuccessModel(right))
})
// 仅获取权限
router.get('/list/only', (req, res, next) => {
  const rights = getAuthorityList()
  return rights.then(rows => {
    res.json(new SuccessModel(rows))
  })
})
// 角色新增权限（实现多个权限的更新）
router.post('/new', async (req, res, next) => {
  const result = await newAuthority(req.body)
  if (!result) {
    res.json(new ErrorModel('添加权限失败'))
  } else {
    res.json(new SuccessModel('添加权限成功'))
  }
})
// 删除角色权限
router.post('/del', (req, res, next) => {
  const result = delAuthority(req.body)
  return result.then(val => {
    if (val) {
      res.json(new SuccessModel('删除权限成功'))
    } else {
      res.json(new ErrorModel('删除权限失败'))
    }
  })
})

/**
 * 前端路由index.js； /detail
 */
// 根据权限名称获取详情
router.post('/detail', (req, res, next) => {
  const result = getAuthorityDetail(req.body.name)
  return result.then(row => {
    if (row.name) {
      res.json(new SuccessModel())
    } else {
      res.json(new ErrorModel('您当前没有该权限'))
    }
  })
})

module.exports = router
